﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Globalization;
using System.Text.RegularExpressions;

namespace Qpm.Automap.Core.UI
{
  public partial class ResourcePage : Wizard.UI.InternalWizardPage
  {
    public ResourcePage()
    {
      this.Banner.Title = "Step 4 of 4 - Select Resources";
      this.Banner.Subtitle = "Select resouces to be included in report";
      InitializeComponent();
    }

    private void ResourcePage_SetActive(object sender, CancelEventArgs e)
    {
      this.Anchor = AnchorStyles.Right | AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Bottom;
      this.Size = this.Parent.Size;
      SetWizardButtons(Wizard.UI.WizardButtons.Back | Wizard.UI.WizardButtons.Finish);

      if (dgv_Resources.DataSource == null)
      {
        parameters.resources = ProjectReader.GetProjectResources(parameters.tempProjectFile);

        SelectResourcesInConfig(parameters.resources);

        dgv_Resources.DataSource = parameters.resources;

        dgv_Resources.Columns[0].Width = 40;
        dgv_Resources.Columns["UID"].Visible = false;
        dgv_Resources.Columns[1].HeaderText = "";

        for (int i = 1; i < dgv_Resources.Columns.Count; i++)
        {
          dgv_Resources.Columns[i].ReadOnly = true;
        }
      }

    }

    private void ResourcePage_WizardFinish(object sender, CancelEventArgs e)
    {
        XmlDocument xdoc = new XmlDocument();
        if (File.Exists(parameters.configFile))
        {
          xdoc.Load(parameters.configFile);
        }
        else
        {
          XmlElement projectElement = xdoc.CreateElement("Project");
          XmlAttribute nameAttribute = xdoc.CreateAttribute("Name");
          nameAttribute.Value = parameters.projectName;
          projectElement.Attributes.Append(nameAttribute);
          xdoc.AppendChild(projectElement);

          if (!Directory.Exists(parameters.configDirName))
          {
              Directory.CreateDirectory(parameters.configDirName);
          }
        }
        
        InsertContractInfoData(xdoc);
        //Contractor information does not apply in D07A schemas
        //InsertContractorData(xdoc);
        InsertSelectedTasks(xdoc);
        InsertSelectedResources(xdoc);

        xdoc.Save(parameters.configFile);

        XmlDocument projXml = new XmlDocument();
        projXml.Load(parameters.tempProjectFile);
        XmlNamespaceManager xnm = new XmlNamespaceManager(projXml.NameTable);
        string prefix = "p";
        xnm.AddNamespace(prefix, "http://schemas.microsoft.com/project");

        //Creating Network Schedule Report
        CreateNetworkDataReport(projXml, xnm);
        //Create Cost Data Reports
        //First format 1, base object for the rest of the reports.
        CreateCostDataReport(projXml, xnm);
        if (parameters.tempProjectFile != parameters.importFile)
            File.Delete(parameters.tempProjectFile);
      MessageBox.Show("Export finished successfully");
    }

    private static CostDataType CreateCostDataReport(XmlDocument projXml, XmlNamespaceManager xnm)
    {
        //Creat cost data report object
        CostDataType costData = new CostDataType();

        //Create and fill CostReportDocumenType Section.
        costData.CostReportDocument = new CostReportDocumentType();
        costData.CostReportDocument.CreationDateTime = DateTime.Now.ToString("s");
        costData.CostReportDocument.SubmissionDateTime = DateTime.Now.ToString("s");
        costData.CostReportDocument.Description = new TextType("Cost Data Report for project " + parameters.projectName);


        //Get project start and end dates
        XmlNode projStartNode = projXml.DocumentElement.SelectSingleNode("p:StartDate", xnm);
        XmlNode projEndNode = projXml.DocumentElement.SelectSingleNode("p:FinishDate", xnm);
        System.DateTime projStartDate = System.DateTime.Parse(projStartNode.InnerText);
        System.DateTime projEndDate = System.DateTime.Parse(projEndNode.InnerText);
        costData.CostReportDocument.EffectiveBasePeriod = new BasePeriodType(projStartDate.ToString("s"), projEndDate.ToString("s"));


        //Get tasks for WBS Sections
        DataTable taskTable = parameters.tasks;
        //Only use the tasks selected in the tool
        DataRow[] tasks = taskTable.Select("Select <> 0");
        //List of Top Reporting Nodes in report
        List<string> createWBS = new List<string>();
        Dictionary<string, ReportedHierarchicalStructureType> structureNodes = new Dictionary<string, ReportedHierarchicalStructureType>();
        Dictionary<string, ReportingDataNodeType> summaryNodes = new Dictionary<string, ReportingDataNodeType>();
        List<ProjectCostType> projectCostList = new List<ProjectCostType>();

        foreach (DataRow task in tasks)
        {
            string[] wbsParts = task["WBS"].ToString().Split(".".ToCharArray());
            string wbs = string.Empty;
            foreach (string wbsPart in wbsParts)
            {
                if (wbs == string.Empty)
                    wbs += wbsPart;
                else
                    wbs += "." + wbsPart;

                if (!createWBS.Contains(wbs))
                {
                    createWBS.Add(wbs);
                }
            }
        }

        //Create ReportedStructureElement (for Project Summary Task)

        ReportedHierarchicalStructureType taskStructure = new ReportedHierarchicalStructureType();
        //Create list for ProjectCosts. It will later be converted into the ProjectCostType Array needed for the project.

        //Create WBS ID
        string wbsId = CreateTaskNodeID(parameters.projectName);
        wbsId += "WBS";
        taskStructure.ID = new IDType(wbsId);
        taskStructure.Name = new TextType(parameters.projectName + " WBS");
        taskStructure.Description = new TextType(parameters.projectName + " WBS");
        taskStructure.TypeCode = new HierarchicalStructureTypeCodeType();
        taskStructure.TypeCode.Value = HierarchicalStructureTypeCodeContentType.WBS;

        string wbsRerpotedStructureID = "1";
        taskStructure.ComponentReportingDataNode = new ReportingDataNodeType[1];
        taskStructure.ComponentReportingDataNode[0] = new ReportingDataNodeType();
        taskStructure.ComponentReportingDataNode[0].ID = new IDType(wbsRerpotedStructureID);
        taskStructure.ComponentReportingDataNode[0].Name = new TextType(parameters.projectName);
        taskStructure.ComponentReportingDataNode[0].HierarchicalLevelNumeric = 1;

        //Placeholder for Summary ammounts
        double f1Id = 0, f2Id = 0, f3Id = 0, f4Id = 0;
        Regex r = new Regex(@"\s+");
        List<IDType> summCostIdList = new List<IDType>();

        AddFormat1SummaryCosts(projectCostList, summCostIdList);

        f3Id++;
        AddProjectCost(summCostIdList, projectCostList, 0, f3Id.ToString("F30000", CultureInfo.InvariantCulture), "CUMBOP_B", "PMB Beginning of Period (BOP)",
            CostReportingCodeContentType.TOT, CostManagementCodeContentType.BCS);
        f3Id++;
        AddProjectCost(summCostIdList, projectCostList, 0, f3Id.ToString("F30000", CultureInfo.InvariantCulture), "CURBOP_B", "PMB, BOP, Report Period",
            CostReportingCodeContentType.TOT, CostManagementCodeContentType.BCS);
        f3Id++;
        AddProjectCost(summCostIdList, projectCostList, 0, f3Id.ToString("F30000", CultureInfo.InvariantCulture), "periodname_B_BOP", "PMB, BOP, Forecast and Specified Period time frame",
            CostReportingCodeContentType.TOT, CostManagementCodeContentType.BCS);
        f3Id++;
        AddProjectCost(summCostIdList, projectCostList, 0, f3Id.ToString("F30000", CultureInfo.InvariantCulture), "UB_BOP", "PMB, BOP, Undistributed Budget",
            CostReportingCodeContentType.TOT, CostManagementCodeContentType.ZZZ);
        f3Id++;
        AddProjectCost(summCostIdList, projectCostList, 0, f3Id.ToString("F30000", CultureInfo.InvariantCulture), "Depends on line item detail required", "Baseline Changes authorized during the report period",
            CostReportingCodeContentType.TOT, CostManagementCodeContentType.BCS);
        f3Id++;
        AddProjectCost(summCostIdList, projectCostList, 0, f3Id.ToString("F30000", CultureInfo.InvariantCulture), "CUMEOP_B", "PMB, End of Period",
            CostReportingCodeContentType.TOT, CostManagementCodeContentType.BCS);
        f3Id++;
        AddProjectCost(summCostIdList, projectCostList, 0, f3Id.ToString("F30000", CultureInfo.InvariantCulture), "periodname_B_EOP", "PMB, EOP, Forecast and Specified Period time frames",
            CostReportingCodeContentType.TOT, CostManagementCodeContentType.BCS);
        f3Id++;
        AddProjectCost(summCostIdList, projectCostList, 0, f3Id.ToString("F30000", CultureInfo.InvariantCulture), "UB_EOP", "PMB, EOP, Undistributed Budget",
            CostReportingCodeContentType.TOT, CostManagementCodeContentType.ZZZ);

        f4Id++;
        AddProjectCost(summCostIdList, projectCostList, 0, f4Id.ToString("F40000", CultureInfo.InvariantCulture), "CUR_A_" + r.Replace(parameters.projectName, @" "), null,
            CostReportingCodeContentType.TOT, CostManagementCodeContentType.ACP);
        f4Id++;
        AddProjectCost(summCostIdList, projectCostList, 0, f4Id.ToString("F40000", CultureInfo.InvariantCulture), "CUM_A_" + r.Replace(parameters.projectName, @" "), null,
            CostReportingCodeContentType.TOT, CostManagementCodeContentType.ACP);
        f4Id++;
        AddProjectCost(summCostIdList, projectCostList, 0, f4Id.ToString("F40000", CultureInfo.InvariantCulture), "periodname_E_" + r.Replace(parameters.projectName, @" "), null,
            CostReportingCodeContentType.TOT, CostManagementCodeContentType.EST);

        taskStructure.ComponentReportingDataNode[0].AssociatedCostID = summCostIdList.ToArray();

        //taskStructure.ComponentReportingDataNode[0].AssociatedCostID = summaryCostIDs.ToArray();
        taskStructure.ComponentReportingDataNode[0].SubordinateReportingDataNode = new ReportingDataNodeType[0];

        taskStructure.UsedProgressMonitoredProject = new ProgressMonitoredProjectType[] { new ProgressMonitoredProjectType() };
        taskStructure.UsedProgressMonitoredProject[0].ID = new IDType(GetContractString("Contract ID"));
        structureNodes.Add("0", taskStructure);

        foreach (string newWbs in createWBS)
        {
            XmlNode taskNode = projXml.SelectSingleNode("//p:Tasks/p:Task[p:WBS = '" + newWbs + "']", xnm);
            if (taskNode == null)
                continue;
            XmlNode taskNameNode = taskNode.SelectSingleNode("p:Name", xnm);
            XmlNode taskLevelNode = taskNode.SelectSingleNode("p:OutlineLevel", xnm);
            XmlNode taskSummaryNode = taskNode.SelectSingleNode("p:Summary", xnm);
            XmlNode bcwsNode = taskNode.SelectSingleNode("p:BCWS", xnm);
            XmlNode bcwpNode = taskNode.SelectSingleNode("p:BCWP", xnm);
            XmlNode acwpNode = taskNode.SelectSingleNode("p:ACWP", xnm);
            string outlineLevel = taskLevelNode.InnerText;
            string taskName = taskNameNode == null ? parameters.projectName : taskNameNode.InnerText;
            int taskSummary = Convert.ToInt32(taskSummaryNode.InnerText);
            string[] newWbsParts = newWbs.Split(".".ToCharArray());
            string parentWbs = "0";
            if (newWbs.Contains("."))
                parentWbs = newWbs.Substring(0, newWbs.LastIndexOf("."));
            if (newWbsParts.Length == 1 || !summaryNodes.Keys.Contains(parentWbs))
            {
                parentWbs = "0";
                ReportedHierarchicalStructureType reportedNode = structureNodes[parentWbs];
                ReportingDataNodeType parentNode = reportedNode.ComponentReportingDataNode[0];
                ReportingDataNodeType childNode = new ReportingDataNodeType();

                string taskNameId = CreateTaskNodeID(taskName);
                childNode.ID = new IDType(wbsRerpotedStructureID + "." + newWbs);
                childNode.ParentNodeID = new IDType[1];
                childNode.ParentNodeID[0] = new IDType(parentNode.ID.Value);
                childNode.Name = new TextType(taskName);
                childNode.HierarchicalLevelNumeric = Convert.ToDecimal(outlineLevel) + 1;
                childNode.SequenceNumeric = Convert.ToDecimal(newWbsParts[newWbsParts.Length - 1]);

                List<IDType> costIdList = new List<IDType>();

                f1Id++;
                AddProjectCost(costIdList, projectCostList, Convert.ToDecimal(bcwsNode.InnerText), f1Id.ToString("F10000", CultureInfo.InvariantCulture), "CUM_B_" + r.Replace(taskName, @" "), null,
                    CostReportingCodeContentType.DIR, CostManagementCodeContentType.BCS);
                f1Id++;
                AddProjectCost(costIdList, projectCostList, Convert.ToDecimal(bcwpNode.InnerText), f1Id.ToString("F10000", CultureInfo.InvariantCulture), "CUM_P_" + r.Replace(taskName, @" "), null,
                    CostReportingCodeContentType.DIR, CostManagementCodeContentType.BCP);
                f1Id++;
                AddProjectCost(costIdList, projectCostList, Convert.ToDecimal(acwpNode.InnerText), f1Id.ToString("F10000", CultureInfo.InvariantCulture), "CUM_A_" + r.Replace(taskName, @" "), null,
                    CostReportingCodeContentType.DIR, CostManagementCodeContentType.ACP);
                f1Id++;
                AddProjectCost(costIdList, projectCostList, 0, f1Id.ToString("F10000", CultureInfo.InvariantCulture), "RADJ_CV_" + r.Replace(taskName, @" "), null,
                    CostReportingCodeContentType.DIR, CostManagementCodeContentType.VCA);
                f1Id++;
                AddProjectCost(costIdList, projectCostList, 0, f1Id.ToString("F10000", CultureInfo.InvariantCulture), "RADJ_SV_" + r.Replace(taskName, @" "), null,
                    CostReportingCodeContentType.DIR, CostManagementCodeContentType.VSA);
                f1Id++;
                AddProjectCost(costIdList, projectCostList, 0, f1Id.ToString("F10000", CultureInfo.InvariantCulture), "RADJ_B_" + r.Replace(taskName, @" "), null,
                    CostReportingCodeContentType.DIR, CostManagementCodeContentType.CA);
                f1Id++;
                AddProjectCost(costIdList, projectCostList, 0, f1Id.ToString("F10000", CultureInfo.InvariantCulture), "ATC_B_" + r.Replace(taskName, @" "), null,
                    CostReportingCodeContentType.DIR, CostManagementCodeContentType.BCS);
                f1Id++;
                AddProjectCost(costIdList, projectCostList, 0, f1Id.ToString("F10000", CultureInfo.InvariantCulture), "ATC_E_" + r.Replace(taskName, @" "), null,
                    CostReportingCodeContentType.DIR, CostManagementCodeContentType.EST);

                f2Id++;
                AddProjectCost(costIdList, projectCostList, 0, f2Id.ToString("F20000", CultureInfo.InvariantCulture), "CUM_B_" + r.Replace(taskName, @" "), null,
                    CostReportingCodeContentType.DIR, CostManagementCodeContentType.BCS);
                f2Id++;
                AddProjectCost(costIdList, projectCostList, 0, f2Id.ToString("F20000", CultureInfo.InvariantCulture), "CUM_P_" + r.Replace(taskName, @" "), null,
                    CostReportingCodeContentType.DIR, CostManagementCodeContentType.BCP);
                f2Id++;
                AddProjectCost(costIdList, projectCostList, 0, f2Id.ToString("F20000", CultureInfo.InvariantCulture), "CUM_A_" + r.Replace(taskName, @" "), null,
                    CostReportingCodeContentType.DIR, CostManagementCodeContentType.ACP);
                f2Id++;
                AddProjectCost(costIdList, projectCostList, 0, f2Id.ToString("F20000", CultureInfo.InvariantCulture), "RADJ_CV_" + r.Replace(taskName, @" "), null,
                    CostReportingCodeContentType.DIR, CostManagementCodeContentType.VCA);
                f2Id++;
                AddProjectCost(costIdList, projectCostList, 0, f2Id.ToString("F20000", CultureInfo.InvariantCulture), "RADJ_SV_" + r.Replace(taskName, @" "), null,
                    CostReportingCodeContentType.DIR, CostManagementCodeContentType.VSA);
                f2Id++;
                AddProjectCost(costIdList, projectCostList, 0, f2Id.ToString("F20000", CultureInfo.InvariantCulture), "RADJ_B_" + r.Replace(taskName, @" "), null,
                    CostReportingCodeContentType.DIR, CostManagementCodeContentType.CA);
                f2Id++;
                AddProjectCost(costIdList, projectCostList, 0, f2Id.ToString("F20000", CultureInfo.InvariantCulture), "ATC_B_" + r.Replace(taskName, @" "), null,
                    CostReportingCodeContentType.DIR, CostManagementCodeContentType.BCS);
                f2Id++;
                AddProjectCost(costIdList, projectCostList, 0, f2Id.ToString("F20000", CultureInfo.InvariantCulture), "ATC_E_" + r.Replace(taskName, @" "), null,
                    CostReportingCodeContentType.DIR, CostManagementCodeContentType.EST);

                f3Id++;
                AddProjectCost(costIdList, projectCostList, 0, f3Id.ToString("F30000", CultureInfo.InvariantCulture), "CUMBOP_B", "PMB Beginning of Period (BOP)",
                    CostReportingCodeContentType.TOT, CostManagementCodeContentType.BCS);
                f3Id++;
                AddProjectCost(costIdList, projectCostList, 0, f3Id.ToString("F30000", CultureInfo.InvariantCulture), "CURBOP_B", "PMB, BOP, Report Period",
                    CostReportingCodeContentType.TOT, CostManagementCodeContentType.BCS);
                f3Id++;
                AddProjectCost(costIdList, projectCostList, 0, f3Id.ToString("F30000", CultureInfo.InvariantCulture), "periodname_B_BOP", "PMB, BOP, Forecast and Specified Period time frame",
                    CostReportingCodeContentType.TOT, CostManagementCodeContentType.BCS);
                f3Id++;
                AddProjectCost(costIdList, projectCostList, 0, f3Id.ToString("F30000", CultureInfo.InvariantCulture), "UB_BOP", "PMB, BOP, Undistributed Budget",
                    CostReportingCodeContentType.TOT, CostManagementCodeContentType.ZZZ);
                f3Id++;
                AddProjectCost(costIdList, projectCostList, 0, f3Id.ToString("F30000", CultureInfo.InvariantCulture), "Depends on line item detail required", "Baseline Changes authorized during the report period",
                    CostReportingCodeContentType.TOT, CostManagementCodeContentType.BCS);
                f3Id++;
                AddProjectCost(costIdList, projectCostList, 0, f3Id.ToString("F30000", CultureInfo.InvariantCulture), "CUMEOP_B", "PMB, End of Period",
                    CostReportingCodeContentType.TOT, CostManagementCodeContentType.BCS);
                f3Id++;
                AddProjectCost(costIdList, projectCostList, 0, f3Id.ToString("F30000", CultureInfo.InvariantCulture), "periodname_B_EOP", "PMB, EOP, Forecast and Specified Period time frames",
                    CostReportingCodeContentType.TOT, CostManagementCodeContentType.BCS);
                f3Id++;
                AddProjectCost(costIdList, projectCostList, 0, f3Id.ToString("F30000", CultureInfo.InvariantCulture), "UB_EOP", "PMB, EOP, Undistributed Budget",
                    CostReportingCodeContentType.TOT, CostManagementCodeContentType.ZZZ);

                f4Id++;
                AddProjectCost(costIdList, projectCostList, 0, f4Id.ToString("F40000", CultureInfo.InvariantCulture), "CUR_A_" + r.Replace(taskName, @" "), null,
                    CostReportingCodeContentType.TOT, CostManagementCodeContentType.ACP);
                f4Id++;
                AddProjectCost(costIdList, projectCostList, 0, f4Id.ToString("F40000", CultureInfo.InvariantCulture), "CUM_A_" + r.Replace(taskName, @" "), null,
                    CostReportingCodeContentType.TOT, CostManagementCodeContentType.ACP);
                f4Id++;
                AddProjectCost(costIdList, projectCostList, 0, f4Id.ToString("F40000", CultureInfo.InvariantCulture), "periodname_E_" + r.Replace(taskName, @" "), null,
                    CostReportingCodeContentType.TOT, CostManagementCodeContentType.EST);

                childNode.AssociatedCostID = costIdList.ToArray();

                List<ReportingDataNodeType> childNodes = parentNode.SubordinateReportingDataNode.ToList();
                childNodes.Add(childNode);
                parentNode.SubordinateReportingDataNode = childNodes.ToArray();
                if (!summaryNodes.ContainsValue(childNode) && taskSummary == 1)
                {
                    childNode.SubordinateReportingDataNode = new ReportingDataNodeType[0];
                    summaryNodes.Add(newWbs, childNode);
                }
            }
            else
            {
                ReportingDataNodeType parentNode = summaryNodes[parentWbs];
                ReportingDataNodeType childNode = new ReportingDataNodeType();

                string taskNameId = CreateTaskNodeID(taskName);
                childNode.ID = new IDType(wbsRerpotedStructureID + "." + newWbs);
                childNode.ParentNodeID = new IDType[1];
                childNode.ParentNodeID[0] = new IDType(parentNode.ID.Value);
                childNode.Name = new TextType(taskName);
                childNode.HierarchicalLevelNumeric = Convert.ToDecimal(outlineLevel) + 1;
                childNode.SequenceNumeric = Convert.ToDecimal(newWbsParts[newWbsParts.Length - 1]);

                List<IDType> costIdList = new List<IDType>();

                f1Id++;
                AddProjectCost(costIdList, projectCostList, Convert.ToDecimal(bcwsNode.InnerText), f1Id.ToString("F10000", CultureInfo.InvariantCulture), "CUM_B_" + r.Replace(taskName, @" "), null,
                    CostReportingCodeContentType.DIR, CostManagementCodeContentType.BCS);
                f1Id++;
                AddProjectCost(costIdList, projectCostList, Convert.ToDecimal(bcwpNode.InnerText), f1Id.ToString("F10000", CultureInfo.InvariantCulture), "CUM_P_" + r.Replace(taskName, @" "), null,
                    CostReportingCodeContentType.DIR, CostManagementCodeContentType.BCP);
                f1Id++;
                AddProjectCost(costIdList, projectCostList, Convert.ToDecimal(acwpNode.InnerText), f1Id.ToString("F10000", CultureInfo.InvariantCulture), "CUM_A_" + r.Replace(taskName, @" "), null,
                    CostReportingCodeContentType.DIR, CostManagementCodeContentType.ACP);
                f1Id++;
                AddProjectCost(costIdList, projectCostList, 0, f1Id.ToString("F10000", CultureInfo.InvariantCulture), "RADJ_CV_" + r.Replace(taskName, @" "), null,
                    CostReportingCodeContentType.DIR, CostManagementCodeContentType.VCA);
                f1Id++;
                AddProjectCost(costIdList, projectCostList, 0, f1Id.ToString("F10000", CultureInfo.InvariantCulture), "RADJ_SV_" + r.Replace(taskName, @" "), null,
                    CostReportingCodeContentType.DIR, CostManagementCodeContentType.VSA);
                f1Id++;
                AddProjectCost(costIdList, projectCostList, 0, f1Id.ToString("F10000", CultureInfo.InvariantCulture), "RADJ_B_" + r.Replace(taskName, @" "), null,
                    CostReportingCodeContentType.DIR, CostManagementCodeContentType.CA);
                f1Id++;
                AddProjectCost(costIdList, projectCostList, 0, f1Id.ToString("F10000", CultureInfo.InvariantCulture), "ATC_B_" + r.Replace(taskName, @" "), null,
                    CostReportingCodeContentType.DIR, CostManagementCodeContentType.BCS);
                f1Id++;
                AddProjectCost(costIdList, projectCostList, 0, f1Id.ToString("F10000", CultureInfo.InvariantCulture), "ATC_E_" + r.Replace(taskName, @" "), null,
                    CostReportingCodeContentType.DIR, CostManagementCodeContentType.EST);

                f2Id++;
                AddProjectCost(costIdList, projectCostList, 0, f2Id.ToString("F20000", CultureInfo.InvariantCulture), "CUM_B_" + r.Replace(taskName, @" "), null,
                    CostReportingCodeContentType.DIR, CostManagementCodeContentType.BCS);
                f2Id++;
                AddProjectCost(costIdList, projectCostList, 0, f2Id.ToString("F20000", CultureInfo.InvariantCulture), "CUM_P_" + r.Replace(taskName, @" "), null,
                    CostReportingCodeContentType.DIR, CostManagementCodeContentType.BCP);
                f2Id++;
                AddProjectCost(costIdList, projectCostList, 0, f2Id.ToString("F20000", CultureInfo.InvariantCulture), "CUM_A_" + r.Replace(taskName, @" "), null,
                    CostReportingCodeContentType.DIR, CostManagementCodeContentType.ACP);
                f2Id++;
                AddProjectCost(costIdList, projectCostList, 0, f2Id.ToString("F20000", CultureInfo.InvariantCulture), "RADJ_CV_" + r.Replace(taskName, @" "), null,
                    CostReportingCodeContentType.DIR, CostManagementCodeContentType.VCA);
                f2Id++;
                AddProjectCost(costIdList, projectCostList, 0, f2Id.ToString("F20000", CultureInfo.InvariantCulture), "RADJ_SV_" + r.Replace(taskName, @" "), null,
                    CostReportingCodeContentType.DIR, CostManagementCodeContentType.VSA);
                f2Id++;
                AddProjectCost(costIdList, projectCostList, 0, f2Id.ToString("F20000", CultureInfo.InvariantCulture), "RADJ_B_" + r.Replace(taskName, @" "), null,
                    CostReportingCodeContentType.DIR, CostManagementCodeContentType.CA);
                f2Id++;
                AddProjectCost(costIdList, projectCostList, 0, f2Id.ToString("F20000", CultureInfo.InvariantCulture), "ATC_B_" + r.Replace(taskName, @" "), null,
                    CostReportingCodeContentType.DIR, CostManagementCodeContentType.BCS);
                f2Id++;
                AddProjectCost(costIdList, projectCostList, 0, f2Id.ToString("F20000", CultureInfo.InvariantCulture), "ATC_E_" + r.Replace(taskName, @" "), null,
                    CostReportingCodeContentType.DIR, CostManagementCodeContentType.EST);

                f3Id++;
                AddProjectCost(costIdList, projectCostList, 0, f3Id.ToString("F30000", CultureInfo.InvariantCulture), "CUMBOP_B", "PMB Beginning of Period (BOP)",
                    CostReportingCodeContentType.TOT, CostManagementCodeContentType.BCS);
                f3Id++;
                AddProjectCost(costIdList, projectCostList, 0, f3Id.ToString("F30000", CultureInfo.InvariantCulture), "CURBOP_B", "PMB, BOP, Report Period",
                    CostReportingCodeContentType.TOT, CostManagementCodeContentType.BCS);
                f3Id++;
                AddProjectCost(costIdList, projectCostList, 0, f3Id.ToString("F30000", CultureInfo.InvariantCulture), "periodname_B_BOP", "PMB, BOP, Forecast and Specified Period time frame",
                    CostReportingCodeContentType.TOT, CostManagementCodeContentType.BCS);
                f3Id++;
                AddProjectCost(costIdList, projectCostList, 0, f3Id.ToString("F30000", CultureInfo.InvariantCulture), "UB_BOP", "PMB, BOP, Undistributed Budget",
                    CostReportingCodeContentType.TOT, CostManagementCodeContentType.ZZZ);
                f3Id++;
                AddProjectCost(costIdList, projectCostList, 0, f3Id.ToString("F30000", CultureInfo.InvariantCulture), "Depends on line item detail required", "Baseline Changes authorized during the report period",
                    CostReportingCodeContentType.TOT, CostManagementCodeContentType.BCS);
                f3Id++;
                AddProjectCost(costIdList, projectCostList, 0, f3Id.ToString("F30000", CultureInfo.InvariantCulture), "CUMEOP_B", "PMB, End of Period",
                    CostReportingCodeContentType.TOT, CostManagementCodeContentType.BCS);
                f3Id++;
                AddProjectCost(costIdList, projectCostList, 0, f3Id.ToString("F30000", CultureInfo.InvariantCulture), "periodname_B_EOP", "PMB, EOP, Forecast and Specified Period time frames",
                    CostReportingCodeContentType.TOT, CostManagementCodeContentType.BCS);
                f3Id++;
                AddProjectCost(costIdList, projectCostList, 0, f3Id.ToString("F30000", CultureInfo.InvariantCulture), "UB_EOP", "PMB, EOP, Undistributed Budget",
                    CostReportingCodeContentType.TOT, CostManagementCodeContentType.ZZZ);

                f4Id++;
                AddProjectCost(costIdList, projectCostList, 0, f4Id.ToString("F40000", CultureInfo.InvariantCulture), "CUR_A_" + r.Replace(taskName, @" "), null,
                    CostReportingCodeContentType.TOT, CostManagementCodeContentType.ACP);
                f4Id++;
                AddProjectCost(costIdList, projectCostList, 0, f4Id.ToString("F40000", CultureInfo.InvariantCulture), "CUM_A_" + r.Replace(taskName, @" "), null,
                    CostReportingCodeContentType.TOT, CostManagementCodeContentType.ACP);
                f4Id++;
                AddProjectCost(costIdList, projectCostList, 0, f4Id.ToString("F40000", CultureInfo.InvariantCulture), "periodname_E_" + r.Replace(taskName, @" "), null,
                    CostReportingCodeContentType.TOT, CostManagementCodeContentType.EST);


                childNode.AssociatedCostID = costIdList.ToArray();

                List<ReportingDataNodeType> childNodes = parentNode.SubordinateReportingDataNode.ToList();
                childNodes.Add(childNode);
                parentNode.SubordinateReportingDataNode = childNodes.ToArray();
                if (!summaryNodes.ContainsValue(childNode) && taskSummary == 1)
                {
                    childNode.SubordinateReportingDataNode = new ReportingDataNodeType[0];
                    summaryNodes.Add(newWbs, childNode);
                }
            }
        }

        costData.ReportedHierarchicalStructure = structureNodes.Values.ToList().ToArray();

        /*costData.ProgressMonitoredContract = new ProgressMonitoredContractType[1];
        costData.ProgressMonitoredContract[0] = new ProgressMonitoredContractType();
        costData.ProgressMonitoredContract[0].FixedFeeCostAmount = new AmountType(GetContractDecimal("Fixed Fee Cost Amount"));
        costData.ProgressMonitoredContract[0].NonFeeBearingCostAmount = new AmountType(GetContractDecimal("Non Fee Bearing Cost Amount"));
        costData.ProgressMonitoredContract[0].ID = new IDType(GetContractString("Contract ID"));
        string typeCode = GetContractString("Contract Type Code");
        if (typeCode.Length > 0)
        {
            costData.ProgressMonitoredContract[0].TypeCode = new ContractTypeCodeType();
            costData.ProgressMonitoredContract[0].TypeCode.Value = (ContractTypeCodeContentType)Enum.Parse(typeof(ContractTypeCodeContentType), typeCode, true);
        }
        string securityTypeCode = GetContractString("Security Classification Type Code");
        if (securityTypeCode.Length > 0)
        {
            costData.ProgressMonitoredContract[0].SecurityTypeCode = new SecurityClassificationTypeCodeType();
            costData.ProgressMonitoredContract[0].SecurityTypeCode.Value = (SecurityClassificationTypeContentType)Enum.Parse(typeof(SecurityClassificationTypeContentType), securityTypeCode, true);
        }
        costData.ProgressMonitoredContract[0].Name = new TextType(GetContractString("Contract Name"));
        costData.ProgressMonitoredContract[0].TargetPriceAmount = new AmountType(GetContractDecimal("Target Price Amount"));
        costData.ProgressMonitoredContract[0].EstimatedTotalPriceAmount = new AmountType(GetContractDecimal("Estimated Total Price Ammount"));
        costData.ProgressMonitoredContract[0].CeilingPriceAmount = new AmountType(GetContractDecimal("Ceiling Price Ammount"));
        costData.ProgressMonitoredContract[0].EstimatedCeilingPriceAmount = new AmountType(GetContractDecimal("Estimated Ceiling Price Ammount"));
        costData.ProgressMonitoredContract[0].TargetFeePercent = GetContractDecimal("Target Fee Percent").ToString();
        DateTime overTargetBaselineDate = GetContractDateTime("Over Target Baseline Date");
        if (overTargetBaselineDate != DateTime.MinValue)
        {
            costData.ProgressMonitoredContract[0].OverTargetBaselineDate = overTargetBaselineDate;
        }
        costData.ProgressMonitoredContract[0].TargetFeeCostAmount = new AmountType(GetContractDecimal("Target Fee Cost Amount"));
        costData.ProgressMonitoredContract[0].NegotiatedCostAmount = new AmountType(GetContractDecimal("Negotiated Cost Amount"));
        costData.ProgressMonitoredContract[0].CumulativeNegotiatedChangesCostAmount = new AmountType(GetContractDecimal("Cumulative Negotiated Changes Cost Amount"));
        costData.ProgressMonitoredContract[0].AuthorizedUnpricedWorkEstimatedCostAmount = new AmountType(GetContractDecimal("Authorized Unpriced Work Estimated Cost Amount"));
        costData.ProgressMonitoredContract[0].OriginalNegotiatedCostAmount = new AmountType(GetContractDecimal("Original Negotiated Cost Amount"));
        DateTime startDate = GetContractDateTime("Start Date");
        if (startDate != DateTime.MinValue)
        {
            costData.ProgressMonitoredContract[0].StartDate = startDate;
        }
        DateTime defStartDate = GetContractDateTime("Definitization Start Date");
        if (defStartDate != DateTime.MinValue)
        {
            costData.ProgressMonitoredContract[0].DefinitizationStartDate = defStartDate;
        }
        DateTime expectedEndDate = GetContractDateTime("Expected End Date");
        if (expectedEndDate != DateTime.MinValue)
        {
            costData.ProgressMonitoredContract[0].ExpectedEndDate = expectedEndDate;
        }
        DateTime estimatedEndDate = GetContractDateTime("Estimated End Date");
        if (estimatedEndDate != DateTime.MinValue)
        {
            costData.ProgressMonitoredContract[0].EstimatedEndDate = estimatedEndDate;
        }
        DateTime plannedEndDate = GetContractDateTime("Planned End Date");
        if (plannedEndDate != DateTime.MinValue)
        {
            costData.ProgressMonitoredContract[0].PlannedEndDate = plannedEndDate;
        }
        DateTime workStartDate = GetContractDateTime("Work Start Date");
        if (workStartDate != DateTime.MinValue)
        {
            costData.ProgressMonitoredContract[0].WorkStartDate = workStartDate;
        }
        DateTime lidDate = GetContractDateTime("Last Item Delivery Date");
        if (lidDate != DateTime.MinValue)
        {
            costData.ProgressMonitoredContract[0].LastItemDeliveryDate = lidDate;
        }

        costData.ProgressMonitoredContract[0].MinimumAwardFeeCostAmount = new AmountType(GetContractDecimal("Minimum Award Fee Cost Amount"));
        costData.ProgressMonitoredContract[0].MaximumAwardFeeCostAmount = new AmountType(GetContractDecimal("Maximum Award Fee Cost Amount"));
        costData.ProgressMonitoredContract[0].OriginalAwardFeeCostAmount = new AmountType(GetContractDecimal("Original Award Fee Cost Amount"));
        costData.ProgressMonitoredContract[0].CustomerName = new TextType(GetContractString("Customer Name (Program Office Name)"));

        costData.ProgressMonitoredContract[0].IdentifiedContractorParty = parameters.contractorInfo.ToArray();

        costData.ProgressMonitoredContract[0].ReferenceProjectDocument = new ProjectDocumentType[] { new ProjectDocumentType() };
        costData.ProgressMonitoredContract[0].ReferenceProjectDocument[0].TypeCode = new DocumentCodeType();
        costData.ProgressMonitoredContract[0].ReferenceProjectDocument[0].TypeCode.Value = DocumentNameCodeContentType.Item2;
        costData.ProgressMonitoredContract[0].ReferenceProjectDocument[0].Name = new TextType("EVM Acceptance");
        costData.ProgressMonitoredContract[0].ReferenceProjectDocument[0].Description = new TextType(GetContractString("Reference Project Document"));
        costData.ProgressMonitoredContract[0].ReferenceProjectDocument[0].IssueDateTime = GetContractDateTime("Reference Project Document Issue Date").ToString("s");

        costData.ProgressMonitoredContract[0].IncentiveContractPerformanceMeasurement = new ContractPerformanceMeasurementType();
        costData.ProgressMonitoredContract[0].IncentiveContractPerformanceMeasurement.PenaltyCalculationPercent = GetContractDecimal("Penalty Calculation Percent");
        costData.ProgressMonitoredContract[0].IncentiveContractPerformanceMeasurement.BonusCalculationPercent = GetContractDecimal("Bonus Calculation Percent");

        costData.ProgressMonitoredContract[0].ContainedProgressMonitoredProject = new ProgressMonitoredProjectType[1];
        costData.ProgressMonitoredContract[0].ContainedProgressMonitoredProject[0] = new ProgressMonitoredProjectType();
        costData.ProgressMonitoredContract[0].ContainedProgressMonitoredProject[0].ID = new IDType(GetContractString("Project ID"));
        costData.ProgressMonitoredContract[0].ContainedProgressMonitoredProject[0].Name = new TextType(parameters.projectName);
        costData.ProgressMonitoredContract[0].ContainedProgressMonitoredProject[0].Description = new TextType(GetContractString("Description"));
        costData.ProgressMonitoredContract[0].ContainedProgressMonitoredProject[0].TypeCode = new ProjectTypeCodeType();
        costData.ProgressMonitoredContract[0].ContainedProgressMonitoredProject[0].TypeCode.Value = ProjectTypeCodeContentType.ZZZ;

        costData.ProgressMonitoredContract[0].BestCaseEstimateAtCompletionAssociatedProjectCost =
                    new ProjectCostType[] { new ProjectCostType("F1EACa", "BestCaseEAC", "", GetContractDecimal("Best Case Estimate At Completion Associated Project Cost")) };
        costData.ProgressMonitoredContract[0].MostLikelyEstimateAtCompletionAssociatedProjectCost =
            new ProjectCostType[] { new ProjectCostType("F1EACc", "MostLikelyEAC", "", GetContractDecimal("Most Likely Estimate At Completion Associated Project Cost")) };
        costData.ProgressMonitoredContract[0].WorstCaseEstimateAtCompletionAssociatedProjectCost =
            new ProjectCostType[] { new ProjectCostType("F1EACb", "WorstCaseEAC", "", GetContractDecimal("Worst Case Estimate At Competion Associated Project Cost")) };

        //placeholder for ManagementReserver
        ProjectCostType[] mrpcs = costData.ProgressMonitoredContract[0].ContainedProgressMonitoredProject[0].ManagementReserveProjectCost = new ProjectCostType[2];
        mrpcs[0] = new ProjectCostType("F1SUM01", "RADJ_B_MR", "Reprograming Adjustments, Budget", 0, CostManagementCodeContentType.NULL, CostReportingCodeContentType.NULL, null, null);
        mrpcs[1] = new ProjectCostType("F1SUM02", "ATC_B_MR", "BAC", 0, CostManagementCodeContentType.NULL, CostReportingCodeContentType.NULL, null, null);

        //placeholder for UndistributedBudgetProjectCost
        ProjectCostType[] ubpc = costData.ProgressMonitoredContract[0].ContainedProgressMonitoredProject[0].UndistributedBudgetProjectCost = new ProjectCostType[2];
        ubpc[0] = new ProjectCostType("F1SUM03", "ATC_B_UB", "BAC", 0, CostManagementCodeContentType.NULL, CostReportingCodeContentType.NULL, null, null);
        ubpc[1] = new ProjectCostType("F1SUM04", "ATC_E_UB", "EAC", 0, CostManagementCodeContentType.NULL, CostReportingCodeContentType.NULL, null, null);

        //placeholder for OverheadProjectCosts
        ProjectCostType[] opc = costData.ProgressMonitoredContract[0].ContainedProgressMonitoredProject[0].OverheadProjectCost = new ProjectCostType[16];
        opc[0] = new ProjectCostType("F1SUM05", "CUM_B_OH", "Cum budget", 0, CostManagementCodeContentType.NULL, CostReportingCodeContentType.ZZZ, null, null);
        opc[1] = new ProjectCostType("F1SUM06", "CUM_P_OH", "Cum performed", 0, CostManagementCodeContentType.NULL, CostReportingCodeContentType.ZZZ, null, null);
        opc[2] = new ProjectCostType("F1SUM07", "CUM_A_OH", "Cum actual", 0, CostManagementCodeContentType.NULL, CostReportingCodeContentType.ZZZ, null, null);
        opc[3] = new ProjectCostType("F1SUM08", "RADJ_CV_OH", "Reprogramming Adjustment, CV", 0, CostManagementCodeContentType.NULL, CostReportingCodeContentType.ZZZ, null, null);
        opc[4] = new ProjectCostType("F1SUM09", "RADJ_SV_OH", "Reprogramming Adjustment, SV", 0, CostManagementCodeContentType.NULL, CostReportingCodeContentType.ZZZ, null, null);
        opc[5] = new ProjectCostType("F1SUM10", "RADJ_B_OH", "Reprogramming Adjustment, Budget", 0, CostManagementCodeContentType.NULL, CostReportingCodeContentType.ZZZ, null, null);
        opc[6] = new ProjectCostType("F1SUM11", "ATC_B_OH", "BAC", 0, CostManagementCodeContentType.NULL, CostReportingCodeContentType.ZZZ, null, null);
        opc[7] = new ProjectCostType("F1SUM12", "ATC_E_OH", "EAC", 0, CostManagementCodeContentType.NULL, CostReportingCodeContentType.ZZZ, null, null);
        opc[8] = new ProjectCostType("F1SUM13", "CUM_B_GA", "Cum budget", 0, CostManagementCodeContentType.NULL, CostReportingCodeContentType.GA, null, null);
        opc[9] = new ProjectCostType("F1SUM14", "CUM_P_GA", "Cum performed", 0, CostManagementCodeContentType.NULL, CostReportingCodeContentType.GA, null, null);
        opc[10] = new ProjectCostType("F1SUM15", "CUM_A_GA", "Cum actual", 0, CostManagementCodeContentType.NULL, CostReportingCodeContentType.GA, null, null);
        opc[11] = new ProjectCostType("F1SUM16", "RADJ_CV_GA", "Reprogramming Adjustment, CV", 0, CostManagementCodeContentType.NULL, CostReportingCodeContentType.GA, null, null);
        opc[12] = new ProjectCostType("F1SUM17", "RADJ_SV_GA", "Reprogramming Adjustment, SV", 0, CostManagementCodeContentType.NULL, CostReportingCodeContentType.GA, null, null);
        opc[13] = new ProjectCostType("F1SUM18", "RADJ_B_GA", "Reprogramming Adjustment, Budget", 0, CostManagementCodeContentType.NULL, CostReportingCodeContentType.GA, null, null);
        opc[14] = new ProjectCostType("F1SUM19", "ATC_B_GA", "BAC", 0, CostManagementCodeContentType.NULL, CostReportingCodeContentType.GA, null, null);
        opc[15] = new ProjectCostType("F1SUM20", "ATC_E_GA", "EAC", 0, CostManagementCodeContentType.NULL, CostReportingCodeContentType.GA, null, null);

        //placeholder for FundsBorrowedProjectCost
        ProjectCostType[] fbpc = costData.ProgressMonitoredContract[0].ContainedProgressMonitoredProject[0].FundsBorrowedProjectCost = new ProjectCostType[8];
        fbpc[0] = new ProjectCostType("F1SUM21", "CUM_B_COM", "Cum budget", 0, CostManagementCodeContentType.NULL, CostReportingCodeContentType.NULL, null, null);
        fbpc[1] = new ProjectCostType("F1SUM22", "CUM_P_COM", "Cum performed", 0, CostManagementCodeContentType.NULL, CostReportingCodeContentType.NULL, null, null);
        fbpc[2] = new ProjectCostType("F1SUM23", "CUM_A_COM", "Cum actual", 0, CostManagementCodeContentType.NULL, CostReportingCodeContentType.NULL, null, null);
        fbpc[3] = new ProjectCostType("F1SUM24", "RADJ_CV_COM", "Reprogramming Adjustment, CV", 0, CostManagementCodeContentType.NULL, CostReportingCodeContentType.NULL, null, null);
        fbpc[4] = new ProjectCostType("F1SUM25", "RADJ_SV_COM", "Reprogramming Adjustment, SV", 0, CostManagementCodeContentType.NULL, CostReportingCodeContentType.NULL, null, null);
        fbpc[5] = new ProjectCostType("F1SUM26", "RADJ_B_COM", "Reprogramming Adjustment, Budget", 0, CostManagementCodeContentType.NULL, CostReportingCodeContentType.NULL, null, null);
        fbpc[6] = new ProjectCostType("F1SUM27", "ATC_B_COM", "BAC", 0, CostManagementCodeContentType.NULL, CostReportingCodeContentType.NULL, null, null);
        fbpc[7] = new ProjectCostType("F1SUM28", "ATC_E_COM", "EAC", 0, CostManagementCodeContentType.NULL, CostReportingCodeContentType.NULL, null, null);

        costData.ProgressMonitoredContract[0].ContainedProgressMonitoredProject[0].ReportingPlanProjectPeriod = GetContractProjectPeriod("F1 Current Period");
        ProjectReportingCalendarType reportingCalendar_fmt1 = new ProjectReportingCalendarType();
        ProjectReportingCalendarType reportingCalendar_fmt3 = new ProjectReportingCalendarType();
        ProjectReportingCalendarType reportingCalendar_fmt4 = new ProjectReportingCalendarType();
        costData.ProgressMonitoredContract[0].ContainedProgressMonitoredProject[0].BaselineProjectReportingCalendar
            = new ProjectReportingCalendarType[] { reportingCalendar_fmt1, reportingCalendar_fmt3, reportingCalendar_fmt4 };
        reportingCalendar_fmt1.ID = new IDType("F1");
        reportingCalendar_fmt1.Name = new TextType("Current Cum AtComplete");
        ProjectPeriodType currentPeriod = new ProjectPeriodType();
        currentPeriod = GetContractProjectPeriod("F1 Current Period");
        ProjectPeriodType cumToDatePeriod = GetContractProjectPeriod("F1 Cum to Date");
        ProjectPeriodType atCompletePeriod = GetContractProjectPeriod("F1 At Complete");
        List<ProjectPeriodType> projectPeriods = new List<ProjectPeriodType>();
        if (currentPeriod != null) projectPeriods.Add(currentPeriod);
        if (cumToDatePeriod != null) projectPeriods.Add(cumToDatePeriod);
        if (atCompletePeriod != null) projectPeriods.Add(atCompletePeriod);
        reportingCalendar_fmt1.SpecifiedProjectPeriod = projectPeriods.ToArray();

        reportingCalendar_fmt3.ID = new IDType("F3");
        reportingCalendar_fmt3.Name = new TextType("Format 3 Reporting Periods");
        List<ProjectPeriodType> projectPeriods_fmt3 = new List<ProjectPeriodType>();
        List<string> periodNames = new List<string>();
        periodNames.Add("F3 Cum to Date BOP");
        periodNames.Add("F3 Cum to Date EOP");
        periodNames.Add("F3 Current Period BOP");
        periodNames.Add("F3 Forecast Month 1");
        periodNames.Add("F3 Forecast Month 2");
        periodNames.Add("F3 Forecast Month 3");
        periodNames.Add("F3 Forecast Month 4");
        periodNames.Add("F3 Forecast Month 5");
        periodNames.Add("F3 Forecast Month 6");
        periodNames.Add("F3 Out Year 1");
        periodNames.Add("F3 Out Year 2");
        periodNames.Add("F3 Out Year 3");
        periodNames.Add("F3 To Complete");
        foreach (string periodName in periodNames)
        {
            ProjectPeriodType period = GetContractProjectPeriod(periodName);
            if (period != null)
                projectPeriods_fmt3.Add(period);
        }
        reportingCalendar_fmt3.SpecifiedProjectPeriod = projectPeriods_fmt3.ToArray();

        reportingCalendar_fmt4.ID = new IDType("F4");
        reportingCalendar_fmt4.Name = new TextType("Format 4 Reporting Periods");
        List<ProjectPeriodType> projectPeriods_fmt4 = new List<ProjectPeriodType>();
        List<string> periodNames_fmt4 = new List<string>();
        periodNames_fmt4.Add("F4 Current Period");
        periodNames_fmt4.Add("F4 Cum to Date");
        periodNames_fmt4.Add("F4 Forecast Month 1");
        periodNames_fmt4.Add("F4 Forecast Month 2");
        periodNames_fmt4.Add("F4 Forecast Month 3");
        periodNames_fmt4.Add("F4 Forecast Month 4");
        periodNames_fmt4.Add("F4 Forecast Month 5");
        periodNames_fmt4.Add("F4 Forecast Month 6");
        periodNames_fmt4.Add("F4 Out Year 1");
        periodNames_fmt4.Add("F4 Out Year 2");
        periodNames_fmt4.Add("F4 Out Year 3");
        periodNames_fmt4.Add("F4 To Complete");
        foreach (string periodName in periodNames_fmt4)
        {
            ProjectPeriodType period = GetContractProjectPeriod(periodName);
            if (period != null)
                projectPeriods_fmt4.Add(period);
        }
        reportingCalendar_fmt4.SpecifiedProjectPeriod = projectPeriods_fmt4.ToArray();*/

        costData.ProjectCost = projectCostList.ToArray();

        FileStream fsCostFmt1Report = new FileStream(Path.Combine(parameters.outputFolder,
            parameters.projectName + "_CostDataReport_AllFormats_" + string.Format("{0:yyyyMMddHHmmss}", DateTime.Now) +".xml"), FileMode.Create);
        XmlSerializer xsCostFmt1Report = new XmlSerializer(typeof(CostDataType));
        xsCostFmt1Report.Serialize(fsCostFmt1Report, costData);
        fsCostFmt1Report.Close();

        return costData;
    }

    private static void AddFormat1SummaryCosts(List<ProjectCostType> projectCostList, List<IDType> summCostIdList)
    {

        AddProjectCost(summCostIdList, projectCostList, 0, "F1SUM29", "CUM_B_SUBTOTAL", "Cum Budget",
            CostReportingCodeContentType.TOT, CostManagementCodeContentType.BCS);
        AddProjectCost(summCostIdList, projectCostList, 0, "F1SUM30", "CUM_P_SUBTOTAL", "Cum Budget",
            CostReportingCodeContentType.TOT, CostManagementCodeContentType.BCP);
        AddProjectCost(summCostIdList, projectCostList, 0, "F1SUM31", "CUM_A_SUBTOTAL", "Cum Budget",
            CostReportingCodeContentType.TOT, CostManagementCodeContentType.ACP);
        AddProjectCost(summCostIdList, projectCostList, 0, "F1SUM32", "RADJ_CV_SUBTOTAL", "Cum Budget",
            CostReportingCodeContentType.TOT, CostManagementCodeContentType.VCA);
        AddProjectCost(summCostIdList, projectCostList, 0, "F1SUM33", "RADJ_SV_SUBTOTAL", "Cum Budget",
            CostReportingCodeContentType.TOT, CostManagementCodeContentType.VSA);
        AddProjectCost(summCostIdList, projectCostList, 0, "F1SUM34", "RADJ_B_SUBTOTAL", "Cum Budget",
            CostReportingCodeContentType.TOT, CostManagementCodeContentType.CA);
        AddProjectCost(summCostIdList, projectCostList, 0, "F1SUM35", "ACT_B_SUBTOTAL", "Cum Budget",
            CostReportingCodeContentType.TOT, CostManagementCodeContentType.BCS);
        AddProjectCost(summCostIdList, projectCostList, 0, "F1SUM36", "ACT_E_SUBTOTAL", "Cum Budget",
            CostReportingCodeContentType.TOT, CostManagementCodeContentType.EST);
        AddProjectCost(summCostIdList, projectCostList, 0, "F1SUM37", "CUM_B_TOTAL", "Cum Budget",
            CostReportingCodeContentType.TOT, CostManagementCodeContentType.BCS);
        AddProjectCost(summCostIdList, projectCostList, 0, "F1SUM38", "CUM_P_TOTAL", "Cum Budget",
            CostReportingCodeContentType.TOT, CostManagementCodeContentType.BCP);
        AddProjectCost(summCostIdList, projectCostList, 0, "F1SUM39", "CUM_A_TOTAL", "Cum Budget",
            CostReportingCodeContentType.TOT, CostManagementCodeContentType.ACP);
        AddProjectCost(summCostIdList, projectCostList, 0, "F1SUM40", "RADJ_CV_TOTAL", "Cum Budget",
            CostReportingCodeContentType.TOT, CostManagementCodeContentType.VCA);
        AddProjectCost(summCostIdList, projectCostList, 0, "F1SUM41", "RADJ_SV_TOTAL", "Cum Budget",
            CostReportingCodeContentType.TOT, CostManagementCodeContentType.VSA);
        AddProjectCost(summCostIdList, projectCostList, 0, "F1SUM42", "RADJ_B_TOTAL", "Cum Budget",
            CostReportingCodeContentType.TOT, CostManagementCodeContentType.CA);
        AddProjectCost(summCostIdList, projectCostList, 0, "F1SUM43", "ACT_B_TOTAL", "Cum Budget",
            CostReportingCodeContentType.TOT, CostManagementCodeContentType.BCS);
        AddProjectCost(summCostIdList, projectCostList, 0, "F1SUM44", "ACT_E_TOTAL", "Cum Budget",
            CostReportingCodeContentType.TOT, CostManagementCodeContentType.EST);
    }

    private static void AddProjectCost(List<IDType> summaryCostIDs, List<ProjectCostType> projectCosts, decimal? amount, string costID, string costName, string description, CostReportingCodeContentType costReportingType, CostManagementCodeContentType costManagementType)
    {
        summaryCostIDs.Add(new IDType(costID));
        ProjectCostType projectCost = new ProjectCostType(costID, costName, description, amount, CostManagementCodeContentType.NULL, CostReportingCodeContentType.NULL, null, null);
        projectCosts.Add(projectCost);
    }

    private static string GetContractString(string fieldName)
    {
        object value_obj = parameters.contractInfo.Compute("MAX(value)", "FieldName = '" + fieldName + "'");
        if (value_obj == null)
            return "";
        return value_obj.ToString();
    }

    private static string CreateTaskNodeID(string taskName)
    {
        string[] projectName = taskName.Split(" ".ToCharArray());
        string wbsId = "";
        foreach (string word in projectName)
        {
            if (word.Length == 0)
                continue;
            wbsId += word.Substring(0, 1);
        }
        return wbsId;
    }

    private static void CreateNetworkDataReport(XmlDocument projXml, XmlNamespaceManager xnm)
    {
        //Create Report Object
        NetworkScheduleType networkSchedule = new NetworkScheduleType();

        //Create and fill StandardReportDocument Section
        networkSchedule.StandardReportDocument = new StandardReportDocumentType();
        networkSchedule.StandardReportDocument.CreationDateTime = DateTime.Now.ToString("s");
        networkSchedule.StandardReportDocument.Description = new TextType("DCMA Export Tool");
        networkSchedule.StandardReportDocument.EffectiveBasePeriod = new BasePeriodType(DateTime.Now.ToString("s"), DateTime.Now.ToString("s"));

        //List of relationships to be use in report
        List<ProjectScheduleTaskRelationshipType> relationships = new List<ProjectScheduleTaskRelationshipType>();
        List<ProjectScheduleTaskType> taskList = new List<ProjectScheduleTaskType>();
        //Get tasks for Relationships and ProjectScheduleTask Sections
        DataTable taskTable = parameters.tasks;
        //Only use the tasks selected in the tool
        DataRow[] tasks = taskTable.Select("Select <> 0");
        foreach (DataRow row in tasks)
        {
            //Get all relationships where the current task is the successor
            XmlNodeList predecessorNodes = projXml.SelectNodes("//p:Tasks/p:Task[p:UID=" + row["UID"].ToString() + "]/p:PredecessorLink", xnm);
            GetTaskRelationships(xnm, relationships, row, predecessorNodes);

            //Get all relationships where the current task is the predecessor
            XmlNodeList successorNodes = projXml.SelectNodes("//p:Tasks/p:Task/p:PredecessorLink[p:PredecessorUID=" + row["UID"].ToString() + "]", xnm);
            GetTaskRelationships(xnm, relationships, row, predecessorNodes);

            //Get all task data
            XmlNode taskNode = projXml.SelectSingleNode("//p:Tasks/p:Task[p:UID=" + row["UID"].ToString() + "]", xnm);
            GetTaskData(xnm, taskList, row, predecessorNodes, successorNodes, taskNode);
        }
        networkSchedule.ProjectScheduleTaskRelationship = relationships.ToArray();

        networkSchedule.ProgressMonitoredProject = new ProgressMonitoredProjectType();
        DataRow[] projectIDRows = parameters.contractInfo.Select(parameters.contractInfo.Columns[0].ColumnName + " LIKE '" + parameters.ProjectIDFieldName + "'");
        DataRow[] contractIDRows = parameters.contractInfo.Select(parameters.contractInfo.Columns[0].ColumnName + " LIKE '" + parameters.ContractIDFieldName + "'");
        DataRow[] descriptionRows = parameters.contractInfo.Select(parameters.contractInfo.Columns[0].ColumnName + " LIKE '" + parameters.DescriptionFieldName + "'");
        string projectID = (projectIDRows == null || projectIDRows.Length < 1) ? "" : projectIDRows[0].IsNull(1) ? "" : projectIDRows[0][1].ToString();
        string contractID = (contractIDRows == null || contractIDRows.Length < 1) ? "" : contractIDRows[0].IsNull(1) ? "" : contractIDRows[0][1].ToString();
        string description = (descriptionRows == null || descriptionRows.Length < 1) ? "" : descriptionRows[0].IsNull(1) ? "" : descriptionRows[0][1].ToString();
        networkSchedule.ProgressMonitoredProject.ID = new IDType(projectID);
        networkSchedule.ProgressMonitoredProject.ContractID = new IDType(contractID);
        networkSchedule.ProgressMonitoredProject.Description = new TextType(description);
        networkSchedule.ProgressMonitoredProject.Name = new TextType(parameters.projectName);

        //Get project start and end dates
        XmlNode projStart = projXml.DocumentElement.SelectSingleNode("p:StartDate", xnm);
        XmlNode projFinish = projXml.DocumentElement.SelectSingleNode("p:FinishDate", xnm);
        networkSchedule.ProgressMonitoredProject.ReportingPlanProjectPeriod = new ProjectPeriodType();
        networkSchedule.ProgressMonitoredProject.ReportingPlanProjectPeriod.StartDateTime = DateTime.Parse(projStart.InnerText).ToString("s");
        networkSchedule.ProgressMonitoredProject.ReportingPlanProjectPeriod.EndDateTime = DateTime.Parse(projFinish.InnerText).ToString("s");

        networkSchedule.ProjectScheduleTask = taskList.ToArray();

        FileStream fsNetworkReport = new FileStream(Path.Combine(parameters.outputFolder, 
            parameters.projectName + "_NetworkScheduleData_"+string.Format("{0:yyyyMMddHHmmss}", DateTime.Now)+".xml"), FileMode.Create);
        XmlSerializer xsNetworkReport = new XmlSerializer(typeof(NetworkScheduleType));
        xsNetworkReport.Serialize(fsNetworkReport, networkSchedule);
        fsNetworkReport.Close();
    }

    private static void GetTaskData(XmlNamespaceManager xnm, List<ProjectScheduleTaskType> tasks, DataRow row, XmlNodeList predecessorNodes, XmlNodeList successorNodes, XmlNode taskNode)
    {
        ProjectScheduleTaskType task = new ProjectScheduleTaskType();
        task.ID = new IDType(row["UID"].ToString());
        task.DataNodeID = new IDType[1];
        task.DataNodeID[0] = new IDType(row["WBS"].ToString());
        task.Name = new TextType(row["Name"].ToString());

        //Get percent complete
        XmlNode percentCompleteNode = taskNode.SelectSingleNode("p:PercentComplete", xnm);
        if (percentCompleteNode != null)
        {
            task.CalculatedCompletionPercent = Convert.ToDecimal(percentCompleteNode.InnerText);
        }

        //Get Task TypeCode
        XmlNode milestoneNode = taskNode.SelectSingleNode("p:Milestone", xnm);
        XmlNode summaryNode = taskNode.SelectSingleNode("p:Summary", xnm);
        task.TypeCode = new ScheduleTaskTypeCodeType();
        //is it a milestone?
        if (Convert.ToInt32(milestoneNode.InnerText)==1)
        {
            task.TypeCode.Value = ScheduleTaskTypeContentType.MS;
        }
        //is it a summary task?
        else if (Convert.ToInt32(summaryNode.InnerText)==1)
        {
            task.TypeCode.Value = ScheduleTaskTypeContentType.SUM;
        }
        else
        {
            //Default: Activity task
            task.TypeCode.Value = ScheduleTaskTypeContentType.AC;
            // is it a Finish Activity?
            if (predecessorNodes.Count > 0 && successorNodes.Count < 1)
            {
                task.TypeCode.Value = ScheduleTaskTypeContentType.FA;
            }
            //is it a Start Activity?
            if (predecessorNodes.Count < 1 && successorNodes.Count > 0)
            {
                task.TypeCode.Value = ScheduleTaskTypeContentType.SA;
            }
        }

        //Get Task Duration.
        XmlNode durationNode = taskNode.SelectSingleNode("p:Duration", xnm);
        //Convert duration to hours
        decimal duration = 0;
        if (durationNode != null)
        {
            string durationStr = durationNode.InnerText.Replace("PT", "");
            int durationHours = Convert.ToInt32(durationStr.Remove(durationStr.IndexOf("H")));
            int durationMin = Convert.ToInt32(durationStr.Remove(durationStr.IndexOf("M")).Remove(0, durationStr.IndexOf("H") + 1));
            int durationSec = Convert.ToInt32(durationStr.Remove(durationStr.IndexOf("S")).Remove(0, durationStr.IndexOf("M") + 1));
            TimeSpan durationSpan = new TimeSpan(durationHours, durationMin, durationSec);
            duration = Convert.ToDecimal(durationSpan.TotalHours);
        }

        //Get Task Duration Format
        XmlNode durationFmtNode = taskNode.SelectSingleNode("p:DurationFormat", xnm);
        int durationFmt = durationFmtNode == null ? 53 : Convert.ToInt32(durationFmtNode.InnerText);

        //Convert Durationt to correct format
        task.TotalDurationMeasure = new DurationMeasureType();
        if (durationFmt == 3 || durationFmt == 4 || durationFmt == 35 || durationFmt == 36)
        {
            task.TotalDurationMeasure.unitCode = MeasurementUnitCommonCodeDurationContentType.MIN;
            task.TotalDurationMeasure.Value = duration * 60;
        }
        //Convert to days:
        else if (durationFmt == 7 || durationFmt == 8 || durationFmt == 39 || durationFmt == 40)
        {
            task.TotalDurationMeasure.unitCode = MeasurementUnitCommonCodeDurationContentType.DAY;
            task.TotalDurationMeasure.Value = duration / 8;
        }
        //Convert to weeks:
        else if (durationFmt == 9 || durationFmt == 10 || durationFmt == 41 || durationFmt == 42)
        {
            task.TotalDurationMeasure.unitCode = MeasurementUnitCommonCodeDurationContentType.W4;
            task.TotalDurationMeasure.Value = duration / 80;
        }
        //Convert to months:
        else if (durationFmt == 11 || durationFmt == 12 || durationFmt == 43 || durationFmt == 44)
        {
            task.TotalDurationMeasure.unitCode = MeasurementUnitCommonCodeDurationContentType.MON;
            task.TotalDurationMeasure.Value = duration / 160;
        }
        //Convert to percent:
        else if (durationFmt == 19 || durationFmt == 20 || durationFmt == 51 || durationFmt == 52)
        {
            task.TotalDurationMeasure.unitCode = MeasurementUnitCommonCodeDurationContentType.HUR;
            task.TotalDurationMeasure.Value = duration;
        }
        //If format is null:
        else
        {
            task.TotalDurationMeasure.unitCode = MeasurementUnitCommonCodeDurationContentType.HUR;
            task.TotalDurationMeasure.Value = duration;
        }

        //Get Actual Start and Finish Dates
        XmlNode actStart = taskNode.SelectSingleNode("p:ActualStart", xnm);
        XmlNode actFinish = taskNode.SelectSingleNode("p:ActualFinish", xnm);
        //Set Actual start and finish dates
        if (actStart != null || actFinish != null)
        {
            task.ActualScheduledBasePeriod = new BasePeriodType();
            if (actStart != null)
                task.ActualScheduledBasePeriod.StartDateTime = DateTime.Parse(actStart.InnerText).ToString("s");
            if (actFinish != null)
                task.ActualScheduledBasePeriod.EndDateTime = DateTime.Parse(actFinish.InnerText).ToString("s");
        }

        //Get Baseline Node
        XmlNode BaselineNode = taskNode.SelectSingleNode("p:Baseline[p:Number=0]", xnm);
        if (BaselineNode != null)
        {
            task.BaselineScheduledBasePeriod = new BasePeriodType();
            XmlNode baselineStartNode = taskNode.SelectSingleNode("p:Start", xnm);
            XmlNode basleineFinishNode = taskNode.SelectSingleNode("p:Finish", xnm);
            if (baselineStartNode != null)
                task.BaselineScheduledBasePeriod.StartDateTime = DateTime.Parse(baselineStartNode.InnerText).ToString("s");
            if (basleineFinishNode != null)
                task.BaselineScheduledBasePeriod.EndDateTime = DateTime.Parse(basleineFinishNode.InnerText).ToString("s");
        }
        tasks.Add(task);
    }

    private static decimal GetContractDecimal(string fieldName)
    {
        object value_obj = parameters.contractInfo.Compute("MAX(value)", "FieldName = '" + fieldName + "'");
        if (value_obj == null)
            return 0;
        decimal value;
        if (decimal.TryParse(value_obj.ToString(), out value))
            return value;
        return 0;
    }
    private static ProjectPeriodType GetContractProjectPeriod(string fieldName)
    {
        object value_obj = parameters.contractInfo.Compute("MAX(value)", "FieldName = '" + fieldName + "'");
        if (value_obj == null)
            return null;
        string fieldValue = value_obj.ToString();
        if (fieldValue.Trim().Length == 0)
            return null;
        StringReader sr = new StringReader(fieldValue);
        XmlSerializer xs = new XmlSerializer(typeof(ProjectPeriodType));
        object obj = xs.Deserialize(sr);
        if (obj != null)
        {
            return obj as ProjectPeriodType;
        }
        return null;
    }
    private static DateTime GetContractDateTime(string fieldName)
    {
        object value_obj = parameters.contractInfo.Compute("MAX(value)", "FieldName = '" + fieldName + "'");
        if (value_obj == null)
            return DateTime.MinValue;
        DateTime value;
        if (DateTime.TryParse(value_obj.ToString(), out value))
            return value;
        return DateTime.MinValue;
    }

    private static void GetTaskRelationships(XmlNamespaceManager xnm, List<ProjectScheduleTaskRelationshipType> relationships, DataRow row, XmlNodeList predecessorNodes)
    {
        if (predecessorNodes.Count > 0)
        {
            string relationshipID = "TR000";
            int relId = 1;
            foreach (XmlNode predecessorNode in predecessorNodes)
            {
                ProjectScheduleTaskRelationshipType relationship = new ProjectScheduleTaskRelationshipType();
                relationship.ID = new IDType();
                relationship.ID.Value = relationshipID.Remove(relationshipID.Length - relId.ToString().Length);
                relationship.ID.Value += relId.ToString();
                relId++;

                XmlNode typeNode = predecessorNode.SelectSingleNode("p:Type", xnm);
                relationship.TypeCode = new ScheduleTaskRelationshipTypeCodeType();
                switch (typeNode.InnerText)
                {
                    case "1": relationship.TypeCode.Value = ScheduleTaskRelationshipTypeContentType.F2S;
                        break;
                    case "2": relationship.TypeCode.Value = ScheduleTaskRelationshipTypeContentType.S2S;
                        break;
                    case "3": relationship.TypeCode.Value = ScheduleTaskRelationshipTypeContentType.F2F;
                        break;
                    case "4": relationship.TypeCode.Value = ScheduleTaskRelationshipTypeContentType.S2F;
                        break;
                    default: relationship.TypeCode.Value = ScheduleTaskRelationshipTypeContentType.F2S;
                        break;
                }

                XmlNode uidNode = predecessorNode.SelectSingleNode("p:PredecessorUID", xnm);
                string predecessorUid = uidNode.InnerText;
                string successorUid = row["UID"].ToString();

                relationship.PredecessorSpecifiedProjectScheduleTask = new ProjectScheduleTaskType[1];
                relationship.PredecessorSpecifiedProjectScheduleTask[0] = new ProjectScheduleTaskType();
                relationship.PredecessorSpecifiedProjectScheduleTask[0].ID = new IDType(predecessorUid);

                relationship.SuccessorSpecifiedProjectScheduleTask = new ProjectScheduleTaskType[1];
                relationship.SuccessorSpecifiedProjectScheduleTask[0] = new ProjectScheduleTaskType();
                relationship.SuccessorSpecifiedProjectScheduleTask[0].ID = new IDType(successorUid);

                relationships.Add(relationship);
            }
        }
    }

    private void button5_Click(object sender, EventArgs e)
    {
      DataTable table = dgv_Resources.DataSource as DataTable;
      foreach (DataRow row in table.Rows)
      {
        row["Select"] = true;
      }
    }

    private void button7_Click(object sender, EventArgs e)
    {
      DataTable table = dgv_Resources.DataSource as DataTable;
      foreach (DataRow row in table.Rows)
      {
        row["Select"] = false;
      }
    }

    private void SelectResourcesInConfig(DataTable resTable)
    {
      if (!File.Exists(parameters.configFile))
        return;

      XmlDocument xdoc = new XmlDocument();
      xdoc.Load(parameters.configFile);

      XmlNodeList taskNodes = xdoc.SelectNodes("//SelectedResources/ResUID");
      foreach (XmlElement taskElement in taskNodes)
      {
        int taskUid = taskElement.InnerText == null || taskElement.InnerText.Trim().Length == 0 ? -1 : Convert.ToInt32(taskElement.InnerText);
        if (taskUid < 0)
          continue;
        DataRow[] taskRows = resTable.Select("UID = " + taskUid.ToString());
        foreach (DataRow taskRow in taskRows)
        {
          taskRow["Select"] = true;
        }
      }
    }

    private void InsertContractInfoData(XmlDocument xdoc)
    {
      string contractNodeName = "ContractInfo";
      XmlElement contractInfoNode = xdoc.DocumentElement.SelectSingleNode("//" + contractNodeName) as XmlElement;
      if (contractInfoNode == null)
      {
        contractInfoNode = xdoc.CreateElement(contractNodeName);
        xdoc.DocumentElement.AppendChild(contractInfoNode);
      }
      DataTable contractsTable = parameters.contractInfo;
      foreach (DataRow row in contractsTable.Rows)
      {
        XmlElement fieldNode;
        string fieldName = row["FieldName"].ToString();

        fieldNode = xdoc.SelectSingleNode("//" + contractNodeName + "/Field[@Name='" + fieldName + "']") as XmlElement;
        if (fieldNode == null)
        {
          fieldNode = xdoc.CreateElement("Field");
          XmlAttribute fieldNameAtt = xdoc.CreateAttribute("Name");
          fieldNameAtt.Value = fieldName;
          fieldNode.Attributes.Append(fieldNameAtt);
          contractInfoNode.AppendChild(fieldNode);
        }
        fieldNode.InnerText = row["Value"].ToString();
      }
    }

    private void InsertContractorData(XmlDocument xdoc)
    {
        string contractorNodeName = "ContractorData";
        XmlElement contractorNode = xdoc.DocumentElement.SelectSingleNode("//" + contractorNodeName) as XmlElement;
        if (contractorNode == null)
        {
            contractorNode = xdoc.CreateElement(contractorNodeName);
            xdoc.DocumentElement.AppendChild(contractorNode);
        }

        StringWriter sw = new StringWriter();
        XmlSerializer xsCostFmt1Report = new XmlSerializer(typeof(ContractorPartyType[]));
        xsCostFmt1Report.Serialize(sw, parameters.contractorInfo.ToArray());
        contractorNode.InnerText = sw.ToString();
    }

    private void InsertSelectedTasks(XmlDocument xdoc)
    {
      string sTaskNodeName = "SelectedTasks";
      XmlElement sTaskNode = xdoc.DocumentElement.SelectSingleNode("//" + sTaskNodeName) as XmlElement;
      if (sTaskNode == null)
      {
        sTaskNode = xdoc.CreateElement(sTaskNodeName);
        xdoc.DocumentElement.AppendChild(sTaskNode);
      }
      else
      {
        sTaskNode.RemoveAll();
      }
      DataTable taskTable = parameters.tasks;
      DataRow[] tasks = taskTable.Select("Select <> 0");
      foreach (DataRow row in tasks)
      {
        XmlElement uidElement = xdoc.CreateElement("TaskUID");
        uidElement.InnerText = row["UID"].ToString();
        sTaskNode.AppendChild(uidElement);
      }
    }

    private void InsertSelectedResources(XmlDocument xdoc)
    {
      string sResNodeName = "SelectedResources";
      XmlElement sResNode = xdoc.DocumentElement.SelectSingleNode("//" + sResNodeName) as XmlElement;
      if (sResNode == null)
      {
        sResNode = xdoc.CreateElement(sResNodeName);
        xdoc.DocumentElement.AppendChild(sResNode);
      }
      else
      {
        sResNode.RemoveAll();
      }
      DataTable resTable = dgv_Resources.DataSource as DataTable;
      DataRow[] resources = resTable.Select("Select <> 0");
      foreach (DataRow row in resources)
      {
        XmlElement uidElement = xdoc.CreateElement("ResUID");
        uidElement.InnerText = row["UID"].ToString();
        sResNode.AppendChild(uidElement);
      }
    }
  }
}
